#!/bin/bash
# Exit on error
set -e
GIT_ROOT="$(git rev-parse --show-toplevel)"

pushd "$GIT_ROOT/LinuxInstall/package/Debian"

# Build Deb package

TAP_DIR="opentap/usr/share/opentap"
mkdir -p opentap/DEBIAN
mkdir -p opentap/usr/bin
mkdir -p $TAP_DIR
mkdir -p opentap/usr/share/doc/opentap

cp "$GIT_ROOT/LICENSE.txt" opentap/usr/share/doc/opentap/copyright

echo "Extracting opentap"
unzip -q ../OpenTAP.TapPackage -d $TAP_DIR

pushd $TAP_DIR
chmod +x tap
popd
pushd opentap/usr/bin
ln -s ../share/opentap/tap
popd

BYTES=$(du -sb opentap | cut -f1)
DIVISOR=1024

# Size in KB, rounded up -- addition and subtraction is necessary because we're using integer division
SIZE_KB=$(((BYTES - 1) / DIVISOR + 1))

# sed control-debian -e "s/@VERSION@/$VERSION/g" -e "s/@SIZE_KB@/$SIZE_KB/g" > opentap/DEBIAN/control
cp postinst.in opentap/DEBIAN/postinst
chmod 0555 opentap/DEBIAN/postinst
chmod +x opentap/DEBIAN/postinst

VERSION="$(./$TAP_DIR/tap sdk gitversion)"
# The last character in the version specifier cannot be a '-'
while [ "${VERSION: -1}" = "-" ]; do
    VERSION="${VERSION::-1}"
done

sed control.in -e "s/\$(GitVersion)/$VERSION/g" -e "s/@SIZE_KB@/$SIZE_KB/g" > opentap/DEBIAN/control

# Don't package log file generated from gitversion
rm -rf ./$TAP_DIR/SessionLogs/*

chmod 755 opentap/DEBIAN

echo "Building .deb package"
dpkg --build opentap

mv opentap.deb ..

echo "Built .deb package"
